package com.liuyfly.leetcode.util;

import java.util.ArrayList;
import java.util.List;

import com.liuyfly.leetcode.model.TreeNode;

/**
 * @author liuyangfang at 2022-10-19 16:17
 */
public class TreeNodeUtil {
    public static <T> List<T> preorderTraversal(TreeNode<T> node) {
        List<T> result = new ArrayList<>();
        preorder(node, result);
        return result;
    }

    public static <T> List<T> inorderTraversal(TreeNode<T> node) {
        List<T> result = new ArrayList<>();
        inorder(node, result);
        return result;
    }

    public static <T> List<T> postorderTraversal(TreeNode<T> node) {
        List<T> result = new ArrayList<>();
        postorder(node, result);
        return result;
    }

    private static <T> void preorder(TreeNode<T> node, List<T> list) {
        if (node == null) {
            return;
        }
        list.add(node.val);
        preorder(node.left, list);
        preorder(node.right, list);
    }

    private static <T> void inorder(TreeNode<T> node, List<T> list) {
        if (node == null) {
            return;
        }
        inorder(node.left, list);
        list.add(node.val);
        inorder(node.right, list);
    }

    private static <T> void postorder(TreeNode<T> node, List<T> list) {
        if (node == null) {
            return;
        }
        postorder(node.left, list);
        postorder(node.right, list);
        list.add(node.val);
    }
}
